const {
  getUser,
  getProject,
  getReadme,
  getFollowings
} = require('./api/user.js')

module.exports = function (api) {
  api.loadSource(async ({ addCollection }) => {
    // github 个人信息
    let userData = {}
    // 开源项目
    const projectData = []
    // 关注
    const followingDate = []

    try {
      userData = await getUser()

      const p = await getProject()
      for (const pro of p) {
        const item = {
          id: pro.name,
          name: pro.name,
          description: pro.description,
          createTime: pro.created_at,
          updateTime: pro.updated_at,
          stargazersCount: pro.stargazers_count,
          watchersCount: pro.watchers_count,
          forksCount: pro.forks_count,
          url: pro.html_url,
          language: pro.language,
          license: pro.license && pro.license.spdx_id
        }

        const readme = await getReadme(pro.name)

        item.readme = readme.content
        projectData.push(item)
      }

      const f = await getFollowings()
      f.forEach(item => {
        followingDate.push({
          name: item.login,
          url: item.html_url,
          avatar: item.avatar_url
        })
      })
    } catch (error) {
      throw new Error(`${error.config.url}: ${error.code}`)
    }

    const user = addCollection('User')
    const project = addCollection('Project')
    const following = addCollection('Following')

    user.addNode(userData)
    projectData.forEach(item => project.addNode(item))
    followingDate.forEach(item => following.addNode(item))
    
  })

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  })
}
